# coding=UTF-8
import os
from utils import read_config, macd_util_v1, date_util, json_util, excel_util, doc_util
from service import data_service

base_path = read_config.base_path
config_path = os.path.join(read_config.data_path, 'common', 'config')


# 月 macd 上穿0轴
def month_cross(s_dict):
    result_path = os.path.join(read_config.data_path, 'result', '月macd', date_util.find_last_valid_day(), '跑批结果')
    has_run_dict = []
    if os.path.exists(result_path):
        has_run_dict = doc_util.get_doc_str_list(os.path.join(result_path, '记录跑批完成'))
    else:
        content_arr = [['编码', '名称', '上上月macd', '上月macd', '本月macd']]
        excel_util.gen_an_excel(result_path, '月macd跑批', '', content_arr)
    if len(s_dict) == 0:
        s_dict = data_service.new_stock_all()
    count = 0
    for code in s_dict:
        if code in has_run_dict:  # 已经完成
            continue
        has_run_dict.append(code)
        count += 1
        if count % 100 == 0 or count == len(s_dict):
            doc_util.gen_new_doc(result_path, '记录跑批完成', has_run_dict)
        macd_list = macd_util_v1.get_macd_list(code, date_util.get_date_str(), 3, 30)
        if len(macd_list) < 3:
            print(code + '这支股票不太行')
            continue
        macd_info0 = json_util.to_json(macd_list[0])
        macd_info1 = json_util.to_json(macd_list[1])
        macd_info2 = json_util.to_json(macd_list[2])
        macd0 = macd_info0['macd']
        macd1 = macd_info1['macd']
        macd2 = macd_info2['macd']
        if macd0 > 0 and macd1 > 0:
            continue
        if (macd0 >= 0 and macd1 < 0) or (macd2 < macd1 < macd0 < 0 and macd0 > -0.01):
            row_info = []
            row_info.append(code)
            row_info.append(s_dict[code]['name'])
            row_info.append(round(macd2, 4))
            row_info.append(round(macd1, 4))
            row_info.append(round(macd0, 4))
            excel_util.add_n_row(os.path.join(result_path, '月macd跑批.xlsx'), '', [row_info])


if __name__ == '__main__':
    s_dict = doc_util.get_a_doc_dict(os.path.join(read_config.data_path, 'common', 'users', 't1qznXH'), 'code')
    month_cross(s_dict)
